package com.bdqn.shiro;

import com.bdqn.pojo.User;
import com.bdqn.service.UserService;
import jakarta.annotation.Resource;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;


/**
 * MyShiroRealm（安全数据源）
 *
 * @author LILIBO
 * @since 2024-10-15
 */
public class MyShiroRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;

    /**
     * 自定义认证流程（机制）
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("调用 MyShiroRealm.doGetAuthenticationInfo 获取身份信息！");
        // 获得身份信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String userName = token.getUsername();

        // 从数据库中根据用户名查询用户对象（联表查询，包含角色信息）
        User user = userService.getByUsrName(userName);
        if (user == null) {
            throw new UnknownAccountException("用户不存在"); // 用户不存在
        }
        if (user.getUsrFlag() == null || user.getUsrFlag() == 0) {
            throw new LockedAccountException("账号已锁定");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getUsrPassword(), this.getName());
        // 返回身份信息
        return info;
    }

    /**
     * 自定义授权（认证通过才会授权）
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("调用 MyShiroRealm.doGetAuthorizationInfo 获取权限信息！");
        // 获得权限信息
        User user = (User) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        // 静态授权：授予主体(用户)相应的角色和权限
        info.addRole(user.getRole().getRoleName());
        info.addStringPermission("用户列表"); // 所有用户拥有"用户列表"权限
        if ("管理员".equals(user.getRole().getRoleName())) { // 管理员拥有"增删改"权限
            info.addStringPermission("用户添加");
            info.addStringPermission("用户编辑");
            info.addStringPermission("用户删除");
        }

        // 返回授权信息
        return info;
    }

}
